package com.yituo.mjworld.mvc.entity;

import com.alibaba.fastjson.JSONObject;
import com.yituo.mjworld.core.utils.ApplicationContextHolder;
import com.yituo.mjworld.mvc.entity.other.MoblieCode;
import com.yituo.mjworld.mvc.entity.web.OtherToken;
import com.yituo.mjworld.mvc.entity.web.WebUser;
import com.yituo.mjworld.mvc.entity.web.WxCache;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户数据类.
 * <p>
 * 缓存用户数据.
 *
 * @author Administrator
 */
public class UserData {


  public static String uploadPath = "";
  /**
   * 微信登录要用到的缓存
   */
  public static Map<String, WxCache> wxCacheMap;
  /**
   * code list.存储wx登录后颁发的code,后续页面通过这个code来申请token
   */
  public static List<String> code;
  public static Map<String, MoblieCode> moblieCodeMap;
  /**
   * 静默注册页一次有效的缓存数据
   */
  public static Map<String, String> data = new HashMap<String, String>(16);
  /**
   * 所有本站已经ban 发的token
   */
  private static Map<String, OtherToken> tokenMap;
  /**
   * 所有的用户数据
   */
  private static Map<String, WebUser> userMap;
  /**
   * 权限表
   */
  private static Map<Integer, String> ruleMap;

  public static String getUploadPath() {
    return uploadPath;
  }

  public static void setUploadPath(String uploadPath) {
    UserData.uploadPath = uploadPath;
  }

  public static Map<String, WxCache> getWxCacheMap() {
    return wxCacheMap;
  }

  public static List<String> getCode() {
    return code;
  }

  public static void setCode(List<String> code) {
    UserData.code = code;
  }

  public static Map<String, MoblieCode> getMoblieCodeMap() {
    return moblieCodeMap;
  }

  public static void setMoblieCodeMap(Map<String, MoblieCode> moblieCodeMap) {
    UserData.moblieCodeMap = moblieCodeMap;
  }

  public static Map<String, OtherToken> getTokenMap() {
    return tokenMap;
  }

  public static void setTokenMap(Map<String, OtherToken> tokenMap) {
    UserData.tokenMap = tokenMap;
  }

  public static Map<String, WebUser> getUserMap() {
    return userMap;
  }

  public static void setUserMap(Map<String, WebUser> userMap) {
    UserData.userMap = userMap;
  }

  public static Map<Integer, String> getRuleMap() {
    return ruleMap;
  }

  public static void setRuleMap(Map<Integer, String> ruleMap) {
    UserData.ruleMap = ruleMap;
  }

  /**
   * 初始化用户数据缓存.
   * 由Spring 进行初始化
   */
  public static void init() {
    if (tokenMap == null && userMap == null) {
      tokenMap = new HashMap<String, OtherToken>(16);
      userMap = new HashMap<String, WebUser>(16);
      ruleMap = new HashMap<Integer, String>(16);
      moblieCodeMap = new HashMap<String, MoblieCode>(16);
      code = new ArrayList<String>();
      wxCacheMap = new HashMap<String, WxCache>(16);
      getData();
    }
  }

  /**
   * 销毁.
   * <p>
   * 持久化对象
   */
  public static void destroy() {
    // 1.保存所有的token对象
    SessionFactory sf = (SessionFactory) ApplicationContextHolder.getBean("sessionFactory");
    Session session = sf.openSession();
    Transaction tx = session.beginTransaction();
    for (String key : tokenMap.keySet()) {
      session.save(tokenMap.get(key));
    }
    for (String key : wxCacheMap.keySet()) {
      session.save(wxCacheMap.get(key));
    }
    tx.commit();
    session.close();
    System.gc();
  }

  /**
   * 获取用户
   *
   * @return
   */
  public static WebUser getUser(String userId) {
    return userMap.get(userId);
  }

  /**
   * 置入/更新用户
   *
   * @param user
   */
  public static void putUser(WebUser user) {
    userMap.put(user.getId(), user);
  }


  /**
   * 初始化用户缓存
   */
  private static void getData() {
    //1.读取所有的用户数据
    SessionFactory sf = (SessionFactory) ApplicationContextHolder.getBean("sessionFactory");
    Session session = sf.openSession();
    Transaction tx = session.beginTransaction();
    List<WebUser> userList = session.createQuery("from WebUser ").list();
    List<OtherToken> tokenList = session.createQuery("from OtherToken ").list();
    List<WxCache> wxCacheList = session.createQuery("from WxCache ").list();
//    List<UserRole> ruleList = session.createQuery("from UserRole ").list();
    tx.commit();
    // 2.1先关闭会话,让userList脱离Hibernate Session 的托管,成为游离态.否则接下来的隐藏密码的动作,将直接持久化到Session当中
    session.close();
    //3.缓存所有的用户数据
    if (userList != null) {
      for (WebUser user : userList) {
        user.setPassword("*");
        userMap.put(user.getId(), user);
      }
    }
    if (tokenList != null) {
      for (OtherToken token : tokenList) {
        tokenMap.put(token.getAccounts(), token);
      }
    }
    if (wxCacheList != null) {
      for (WxCache cache : wxCacheList) {
        wxCacheMap.put(cache.getOpenId(), cache);
      }
    }
//    if (ruleList != null) {
//      for (UserRole rule : ruleList) {
//      }
//    }
  }

  /**
   * 设置用户Token
   *
   * @param userId userId
   * @param token  token
   */
  public static void putToken(String userId, OtherToken token) {
    tokenMap.put(userId, token);
  }

  /**
   * 获取用户Token
   *
   * @param uid 欲获取的UID
   */
  public static OtherToken getToken(String uid) {
    OtherToken token = tokenMap.get(uid);
    return token;
  }


  /**
   * 移除用户登录数据
   *
   * @param userId 欲移除的用户ID
   */
  public static void remove(String userId) {
    userMap.remove(tokenMap.get(userId));
    tokenMap.get(userId);
  }

  public static void print() {
    System.out.println(JSONObject.toJSONString(userMap));
  }

}
